<template>
    <full-screen-dialog
        :title="titleMap[mode]"
        v-model="visible"
        :width="1200"
        destroy-on-close
        @closed="$emit('closed')"
    >
        <el-form
            :model="entityObj"
            :rules="rules"
            :disabled="mode == 'Show'"
            ref="dialogForm"
            label-width="100px"
        >
            <el-steps :active="1" align-center finish-status="success">
                <el-step title="已下单" description />
                <el-step title="供应商处理中" description />
                <el-step title="已完成" description />
            </el-steps>

            <el-row style="margin-top: 18px;">
                <el-col :span="8">
                    <el-form-item label-width="120px" label="单据状态:">{{entityObj.statusDesc}}</el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="采购金额:">{{entityObj.purchaseAmount}}</el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item
                        label-width="120px"
                        label="采购订单编号:"
                    >{{entityObj.purchaseOrderCode}}</el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="采购单位:">
                        <el-tooltip placement="top">
                            <template #content>
                                联系人: {{entityObj.purchaseUnityRealName}}
                                <br />
                                联系电话:{{entityObj.purchaseUnityMobile}}
                                <br />
                                联系地址:{{entityObj.purchaseUnityAddress}}
                            </template>
                            <span style="color: blue;">{{entityObj.purchaseUnityName}}</span>
                        </el-tooltip>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="供应商:">
                        <el-tooltip placement="top">
                            <template #content>
                                联系人: {{entityObj.supplierRealName}}
                                <br />
                                联系电话:{{entityObj.supplierMobile}}
                                <br />
                                收货地址:{{entityObj.supplierAddress}}
                            </template>
                            <span style="color: blue;">{{entityObj.supplierName}}</span>
                        </el-tooltip>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="关联要货申请:">{{entityObj.applyOrderCode}}</el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="要货单位:">
                        <el-tooltip placement="top">
                            <template #content>
                                联系人: {{entityObj.realName}}
                                <br />
                                联系电话:{{entityObj.mobile}}
                                <br />
                                收货地址:{{entityObj.address}}
                            </template>
                            <span style="color: blue;">{{entityObj.storeName}}</span>
                        </el-tooltip>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="要货时间:">{{entityObj.applyDate}}</el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="期望到货日期:">{{entityObj.expectedDate}}</el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="下单人:">{{entityObj.createName}}</el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="下单时间:">{{entityObj.createTime}}</el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="最后修改人:">{{entityObj.updateName}}</el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="最后修改时间:">{{entityObj.updateTime}}</el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="下单备注:">{{entityObj.remarks}}</el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="entityObj.purchaseOrderType==1 || entityObj.purchaseOrderType==2">
                <el-col :span="8" v-if="entityObj.purchaseOrderItems" style="color:red">
                    <el-form-item
                        label-width="120px"
                        label="集采确认数量:"
                    >{{entityObj.purchaseOrderItems[0].confirmQty}}</el-form-item>
                </el-col>
                <el-col :span="8" v-if="entityObj.purchaseOrderItems" style="color:red">
                    <el-form-item
                        label-width="120px"
                        label="集采确认备注:"
                    >{{entityObj.purchaseOrderItems[0].confirmRemarks}}</el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" :label="itemName">
                        <el-table
                            :data="entityObj.purchaseOrderItems"
                            border
                            style="width: 100%"
                            show-summary
                            :summary-method="getSummaries"
                        >
                            <!-- <el-table-column label="物料编码" min-width="130" prop="materialCode">
                            </el-table-column>-->
                            <el-table-column label="物料名称" min-width="130">
                                <template #default="scope">
                                    <el-tooltip placement="top" style="width: 80%">
                                        <template #content>{{scope.row.materialCode}}</template>
                                        <div
                                            v-if="scope.row.materialImages && scope.row.materialImages.length > 0"
                                            style="color: #318cf2;"
                                            @click="handlePreview(scope.row)"
                                        >{{scope.row.materialName}}</div>
                                        <div v-else>{{scope.row.materialName}}</div>
                                    </el-tooltip>
                                </template>
                            </el-table-column>
                            <el-table-column label="规格" min-width="120" prop="materialSpecs"></el-table-column>
                            <!-- <el-table-column label="物料类别" min-width="130" prop="materialTypeName">
                            </el-table-column>-->
                            <el-table-column label="单位" min-width="95" prop="unitName"></el-table-column>
                            <el-table-column label="采购单价" min-width="120" prop="price"></el-table-column>
                            <el-table-column label="下单数量" min-width="120" prop="confirmQty"></el-table-column>
                            <el-table-column label="接单数量" min-width="160" prop="receiveQty">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.receiveQty"
                                        :max="scope.row.confirmQty"
                                        style="width: 100%"
                                        :step="1"
                                    ></el-input-number>
                                </template>
                            </el-table-column>
                            <!-- <el-table-column label="金额" min-width="120" prop="totalAmount">
								<template #default="scope">
									{{scope.row.confirmQty*scope.row.price}}
								</template>
                            </el-table-column>-->
                            <el-table-column
                                label="采购模式"
                                min-width="150"
                                prop="supplierSaleTypeDesc"
                                v-if="entityObj.purchaseOrderType==0"
                            ></el-table-column>
                            <el-table-column
                                label="备注"
                                min-width="200"
                                prop="remarks"
                                v-if="entityObj.purchaseOrderType==0"
                            ></el-table-column>
                            <el-table-column
                                label="接单备注"
                                min-width="200"
                                v-if="entityObj.purchaseOrderType==1 ||entityObj.purchaseOrderType==2"
                            >
                                <template #default="scope">
                                    <el-input
                                        v-model="scope.row.receiveRemarks"
                                        style="width: 100%"
                                        :step="1"
                                    ></el-input>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- <el-row>
				<el-form-item style="width: 100%" label-width="120px" label="接单备注:">
					<el-input v-model="entityObj.SupplierRemarks"></el-input>
				</el-form-item>
            </el-row>-->
        </el-form>
        <template #footer>
            <el-button @click="visible = false">取 消</el-button>
            <el-button
                v-if="mode != 'show'"
                type="primary"
                :loading="isSaveing"
                @click="submit()"
            >接 单</el-button>
        </template>

        <!-- <template>
            <el-dialog v-model="materialState" title="选择商品" :width="1000" :center="true" append-to-body
                style="height: 480px">
                <el-row>
                    <sc-material-choice ref="scMaterialChoice"></sc-material-choice>
                </el-row>
                <template #footer>
                    <el-button @click="materialState = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="setMaterialChoice">确定</el-button>
                </template>
            </el-dialog>
        </template>-->
		
		<!-- 预览组件 -->
		<el-image-viewer v-if="showImage" @close="closeViewer" :hide-on-click-modal="true" :url-list="srcList" />
    </full-screen-dialog>
</template>



<script>
import tool from "@/utils/tool";
export default {
    emits: ["success", "closed"],
    data() {
        return {
            mode: "Add",
            titleMap: {
                Add: "新增",
                Edit: "编辑",
                Show: "查看",
            },
            entityObj: {
                purchaseProtocolId: 0,
                purchaseProtocolCode: "",
                purchaseProtocolName: "",
                status: 1,
                crName: "",
                crDate: "",
                supplier: {},
                protocolDate: [],
                purchaseUnityName: "",
                SupplierRemarks: "",
                remarks: "",
                protocolFile: "",
                purchaseProtocolItems: [],
            },
            //预览图片
            previewUrl: [],
            //预览图片列表
            srcList: [],
            showImage: false,
            materialState: false,
            queryList: {},
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            //验证规则
            rules: {
                purchaseProtocolName: [
                    {
                        required: true,
                        type: "string",
                        message: "请填写",
                    },
                ],
                purchaseUnityName: [
                    {
                        required: true,
                        type: "string",
                        message: "请填写",
                    },
                ],
                supplier: [
                    {
                        required: true,
                        type: "object",
                        message: "请填写",
                    },
                ],
                protocolDate: [
                    {
                        required: true,
                        type: "array",
                        message: "请填写",
                    },
                ],
                crName: [
                    {
                        required: true,
                        type: "string",
                        message: "请填写",
                    },
                ],
                crDate: [
                    {
                        required: true,
                        type: "string",
                        message: "请填写",
                    },
                ],
                materialSpecs: [
                    {
                        required: true,
                        type: "string",
                        message: "请填写",
                    },
                ],
                purchaseProtocolItems: [
                    {
                        required: true,
                        type: "array",
                        message: "请填写",
                        trigger: "change",
                    },
                ],
            },
            props: {
                label: "supplierName",
                value: "supplierId",
            },
            materialProps: {
                label: "materialCode",
                value: "materialId",
                items: "materialItems",
            },
            materialTypeTree: [],
            optionsBrand: [],
            optionsUnit: [],
            itemsData: [],
            itemName: "应发货清单:",
        };
    },
    computed: {
        // itemsData() {
        //     let filtered = this.entityObj.purchaseProtocolItems;
        //     if (this.queryList.materialTypeIds&&this.queryList.materialTypeIds.length>0) {
        //         filtered = filtered.filter(item => {
        //             return this.queryList.materialTypeIds.includes(item.materialTypeId);
        //         });
        //     }
        //     if (this.queryList.materialCode) {
        //         filtered = filtered.filter(item => {
        //             return item.materialCode.includes(this.queryList.materialCode);
        //         });
        //     }
        //     if (this.queryList.materialName) {
        //         filtered = filtered.filter(item => {
        //             return item.materialName.includes(this.queryList.materialName);
        //         });
        //     }
        //     return filtered;
        // },
    },
    methods: {
        //显示=
        open(mode = "Add") {
            this.mode = mode;
            this.visible = true;
            return this;
        },
        //图片预览
        handlePreview(row) {
            console.log("row", row.materialImages);
            if (!row.materialImages || row.materialImages.length == 0) {
                return;
            }
            this.previewUrl = row.materialImages[0]; // 设置当前预览的图片 URL
            this.srcList = row.materialImages; // 设置预览列表
            this.showImage = true; // 显示 el-image
        },
        closeViewer() {
            this.showImage = false;
        },
        //表单提交方法
        submit() {
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    try {
                        var returnValue =
                            await this.$API.auth.PostProcessApi.post(
                                this.entityObj.purchaseType==0 ? "purchase-order/receive":"purchase-order/self-receive",
                                {
                                    ...this.entityObj,
                                }
                            );
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$emit("fatherMethod");
                            this.isSaveing = false;
                            this.visible = false;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                            this.isSaveing = false;
                        }
                    } catch (error) {
                        this.loading = false;
                        this.isSaveing = false;
                        return false;
                    }
                }
            });
        },
        //表单注入数据
        async setData(data) {
            if (data.purchaseOrderType == 1) {
                this.itemName = "补发清单:";
                this.titleMap.Add = "接单";
            } else if (data.purchaseOrderType == 2) {
                this.itemName = "退货清单:";
                this.titleMap.Add = "接单";
            }
            data.purchaseOrderItems.map((p) => (p.receiveQty = p.qty));
            this.entityObj = {
                ...data,
                purchaseOrderItems: data.purchaseOrderItems,
            };
            console.log(this.entityObj);
        },
        async initOptions() {
            // try {
            // 	var returnValue = await this.$API.auth.PostProcessApi.post(
            // 		"material-type/tree", {
            // 			status: 1
            // 		}
            // 	);
            // 	if (returnValue.status == 200) {
            // 		this.materialTypeTree = returnValue.response;
            // 	} else {
            // 		this.$message.error("操作失败:" + returnValue.msg);
            // 	}
            // } catch (error) {
            // 	this.loading = false;
            // 	return false;
            // }
        },
        async supplierSelectProcess(rowData) {
            this.entityObj.supplier = {};
            if (rowData) {
                this.entityObj.supplier = {
                    supplierId: rowData.supplierId,
                    supplierName: rowData.supplierName,
                };
            }
            console.log(this.entityObj.supplier);
        },
        addMaterial() {
            this.materialState = true;
        },
        deleteRow(index) {
            this.entityObj.purchaseProtocolItems.splice(index, 1);
        },
        handleSearch() {
            this.itemsData = this.entityObj.purchaseProtocolItems;
            if (
                this.queryList.materialTypeIds &&
                this.queryList.materialTypeIds.length > 0
            ) {
                this.itemsData = this.itemsData.filter((item) => {
                    return this.queryList.materialTypeIds.includes(
                        item.materialTypeId
                    );
                });
            }

            if (this.queryList.materialCode) {
                this.itemsData = this.itemsData.filter((item) => {
                    return item.materialCode.includes(
                        this.queryList.materialCode
                    );
                });
            }

            if (this.queryList.materialName) {
                this.itemsData = this.itemsData.filter((item) => {
                    return item.materialName.includes(
                        this.queryList.materialName
                    );
                });
            }
            console.log(this.entityObj.purchaseProtocolItems);
        },
        setMaterialChoice() {
            let materials = this.$refs.scMaterialChoice.selectionRows;
            materials.map((p) => {
                this.entityObj.purchaseProtocolItems.push({
                    materialId: p.materialId,
                    materialCode: p.materialCode,
                    materialName: p.materialName,
                    materialSpecs: p.materialSpecs,
                    materialTypeId: p.materialTypeId,
                    materialTypeName: p.materialTypeName,
                    unitCode: "",
                    unitName: "",
                    price: 0.0,
                    remarks: "",
                    materialItemId: null,
                    materialItems: p.materialItems,
                });
            });
            this.materialState = false;
            this.queryList = {};
            this.handleSearch();
        },
        formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, "0");
            const day = String(date.getDate()).padStart(2, "0");
            const hours = String(date.getHours()).padStart(2, "0");
            const minutes = String(date.getMinutes()).padStart(2, "0");
            const seconds = String(date.getSeconds()).padStart(2, "0");

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计";
                    return;
                }
                const values = data.map((item) =>
                    Number(item[column.property])
                );

                if (
                    column.property == "confirmQty" ||
                    column.property == "totalAmount"
                ) {
                    if (!values.every((item) => isNaN(item))) {
                        const total = values.reduce((a, b) => a + b, 0);
                        sums[index] = total;
                    }
                }
            });
            return sums;
        },
    },
    async mounted() {
        this.entityObj.purchaseUnityName = tool.data.get("USER_INFO").OrgName;
        this.entityObj.crName = tool.data.get("USER_INFO").Name;
        this.entityObj.crDate = this.formatDate(new Date());
        await this.initOptions();
    },
};
</script>

<style scoped>
.el-form-item {
    margin-bottom: 8px !important;
}
</style>
